package main

import (
	"flag"
	"github.com/nsqio/go-nsq"
	"os"
	"os/signal"
	"syscall"
)

var host string
var topic string
var channel string

type myMessageHandler struct {
	Handler func(content []byte) error
}

// HandleMessage implements the Handler interface.
func (h *myMessageHandler) HandleMessage(m *nsq.Message) error {
	if len(m.Body) == 0 {
		// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.
		// In this case, a message with an empty body is simply ignored/discarded.
		return nil
	}

	// do whatever actual message processing is desired
	err := h.Handler(m.Body)

	// Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message.
	return err
}
func main() {
	flag.StringVar(&host, "host", "127.0.0.1:4161", "nsq lookup host")
	flag.StringVar(&host, "h", "127.0.0.1:4161", "nsq lookup host")
	flag.StringVar(&topic, "topic", "ERROR", "监听频道")
	flag.StringVar(&topic, "t", "ERROR", "监听频道")
	flag.StringVar(&channel, "channel", "default", "监听频道")
	flag.StringVar(&channel, "c", "default", "监听频道")
	flag.Parse()
	config := nsq.NewConfig()
	consumer, err := nsq.NewConsumer(topic, channel, config)
	if err != nil {
		println(err)
	}

	// Set the Handler for messages received by this Consumer. Can be called multiple times.
	// See also AddConcurrentHandlers.
	consumer.AddHandler(&myMessageHandler{
		Handler: func(content []byte) error {
			println(string(content))
			return nil
		},
	})

	// Use nsqlookupd to discover nsqd instances.
	// See also ConnectToNSQD, ConnectToNSQDs, ConnectToNSQLookupds.
	err = consumer.ConnectToNSQLookupd(host)
	if err != nil {
		println(err)
	}

	//wait for signal to exit
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan

	//Gracefully stop the consumer.
	consumer.Stop()

}
